<!--
 * @author  dumeng
 新建/编辑调查问卷
-->
<template>
  <div class="survey-manage">
    <div class="page-title">新建/编辑调查问卷</div>
    <section v-loading="loading" class="page-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px" class="form">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="引导图" prop="coverImgId">
          <image-upload
            :key="uploadImg.imagecropperKey"
            v-model="form.coverImgId"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="702"
            :view="uploadImg.view"
            :height="310"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.briefIntroduction" :rows="2" type="textarea" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="开放范围" prop="openRange">
          <el-radio-group v-model="form.openRange">
            <el-radio v-for="v in dict.KFFW" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.openRange === 'WJKFFW_BM'" label="部门" prop="orgId">
          <el-cascader ref="org" v-model="form.deptIds" style="width: 100%" collapse-tags clearable :props="orgProps" :options="orgTreeData" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束日期"
            default-time="23:59:59"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="最小出题数量" prop="questionNumberMin">
          <el-input v-model="form.questionNumberMin" type="number" placeholder="最小出题数量" />
        </el-form-item>
        <el-form-item label="每题分值" prop="questionScore">
          <el-input v-model="form.questionScore" type="number" placeholder="每题分值" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="v in dict.GIPSTSTUS" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职工端是否展示">
          <el-radio-group v-model="form.isAppVisit">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>
    <section class="page-footer">
      <el-button
        style="padding: 10px 30px"
        @click="
          () => {
            $router.back()
          }
        "
      >取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
  </div>
</template>

<script>
import { getDictByCode, getComAndOrgTree, insert, update, get } from '../api/index'
import { int } from '@/utils/validate'
import { mapGetters } from 'vuex'
export default {
  name: 'SurveyManage',
  data() {
    return {
      dialogMultipleSelections: {},
      fullscreenLoadings: false,
      dialogFormVisibles: false,
      loading: false,
      form: {
        id: '',
        name: '',
        coverImgId: '',
        briefIntroduction: '',
        openRange: '', // 开放范围
        deptIds: [], // 部门
        startTime: '',
        endTime: '',
        questionNumberMin: '', // 最小出题数
        questionScore: '', // 每题得分
        status: '0', // 启用/禁用
        isAppVisit: '1', // app展示/隐藏
        sort: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符',
            trigger: 'blur'
          }
        ],
        coverImgId: [{ required: true, message: '请上传引导图', trigger: 'change' }],
        briefIntroduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
        openRange: [{ required: true, message: '请选择开放范围', trigger: 'change' }],
        deptIds: [{ required: this.form && this.form.openRange === 'WJKFFW_BM', message: '请选择部门', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        questionNumberMin: [{ required: true, message: '请输入题目数量', trigger: 'blur' }],
        questionScore: [{ required: true, message: '请输入分数', trigger: 'blur' }],
        sort: [{ required: false, validator: int, trigger: 'blur' }]

      },
      orgProps: {
        label: 'name',
        value: 'id',
        children: 'list',
        multiple: true,
        emitPath: false,
        checkStrictly: true
      },
      orgTreeData: [],
      state: 'create',
      dict: {
        KFFW: [], // 开放范围
        GIPSTSTUS: [] // 状态

      },
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      showtinymce: false
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getOrgTree()
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    handleCloses(dialogMultipleSelections) {
      this.dialogMultipleSelections = {}
      this.form.bigturntableId = ''
    },
    getOrgTree() {
      return new Promise((resolve, reject) => {
        getComAndOrgTree({ parentId: -1, orgId: this.user.orgId })
          .then((res) => {
            this.orgTreeData = res.data.data
          })
          .catch(() => {
            resolve([])
          })
      })
    },
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['deptIds'] = this.form.deptIds && this.form.deptIds.length > 0 ? this.form.deptIds.join(',') : ''
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.back()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['deptIds'] = this.form.deptIds && this.form.deptIds.length > 0 ? this.form.deptIds.join(',') : ''
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.back()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
            if (this.state === 'update') {
              this.getData(this.$route.query.i)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'deptIds' && data.deptIds) {
                this.form[key] = data.deptIds.split(',').filter((item) => {
                  return item
                })
              } else {
                this.form[key] = data[key]
              }
            }
            console.log(data)
            this.uploadImg.viewId = data.coverImgId
            this.showtinymce = true
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.survey-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .page-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .page-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }
  }
  .page-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
